package com.koron.css2.meterService.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.meterService.bean.MsInfoPlanDetailBean;
import com.koron.css2.meterService.dto.MsInfoPlanDto;
import com.koron.css2.meterService.mapper.MsInfoPlanDetailMapper;
import com.koron.css2.meterService.mapper.MsInfoPlanMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

/**
 * 水表校验
 * @author 周利斌
 *
 */
public class MeterCheck implements ServerInterface{
	
	private static Logger log = LogManager.getLogger(MeterCheck.class);

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		MessageBean<String> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "查询成功", String.class);
		try {
			String factoryNo = JsonUtils.objectToPojo(req.getData(), String.class);
			if(StringUtils.isBlank(factoryNo)) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表表身号不能为空", Void.class);
			}
			MsInfoPlanDetailMapper detailMapper = factory.getMapper(MsInfoPlanDetailMapper.class);	
			MsInfoPlanMapper infoMapper = factory.getMapper(MsInfoPlanMapper.class);
			//MsInfoPlanDetailBean msInfoDetal = detailMapper.selectByFactoryNo(factoryNo);
			MsInfoPlanDetailBean msInfoDetal = detailMapper.selectFromPlanDetailByFactoryNo(factoryNo);
			if(msInfoDetal == null) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表表身号不存在", Void.class);
			}
			if(msInfoDetal.getCheckState()!=null && msInfoDetal.getCheckState() == 1) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "该水表已校验,不能重复校验", Void.class);
			}
			detailMapper.updateCheckState(msInfoDetal.getId(), 1); //修改水表的校验状态为已校验
			MsInfoPlanDto msInfoPlanDto = infoMapper.selectMsInfoPlan(msInfoDetal.getReceiptId());
			int checkAmount = msInfoPlanDto.getCheckAmount() + 1;
			infoMapper.updateCheckAmount(msInfoDetal.getReceiptId(), checkAmount);
			info.setData(String.valueOf(checkAmount));
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription("查询失败");
			log.error(e.getMessage(), e);
		}
		return info;
	}

}
